﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class PropertyDefinitionRule : ILRule<PropertyDefinitionHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public PropertyAttributes Attributes { get; }

        public byte[] Signature { get; }
        public PropertyAccessors Accessors { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandle)]
        public ConstantHandle DefaultValue { get; }

        public PropertyDefinitionRule(
            PropertyAttributes attributes,
            string name,
            byte[] signature)
            : base()
        {
            Attributes = attributes;
            Name = name;
            Signature = signature;
        }

        public PropertyDefinitionRule(MetadataReader reader, PropertyDefinitionHandle propertyDefinitionHandle)
            : base(reader)
        {
            PropertyDefinition propertyDefinition = reader.GetPropertyDefinition(propertyDefinitionHandle);
            Attributes = propertyDefinition.Attributes;
            Name = reader.GetString(propertyDefinition.Name);
            Signature = reader.GetBlobBytes(propertyDefinition.Signature);
            Accessors = propertyDefinition.GetAccessors();
            CustomAttributes = propertyDefinition.GetCustomAttributes();
            DefaultValue = propertyDefinition.GetDefaultValue();
        }

        public override PropertyDefinitionHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            PropertyDefinitionHandle propertyDefinitionHandle = builder.AddProperty(
                attributes: Attributes,
                name: Name == null ? default : builder.GetOrAddString(Name),
                signature: Signature == null ? default : builder.GetOrAddBlob(Signature));
            designer.PropertyDefinitionNumber.Increment();
            return propertyDefinitionHandle;
        }
    }
}